# coding: utf-8
class SuggestionController < ApplicationController

  include ApplicationHelper

  # GET: 加载页面
  def index
    @feedback = Feedback.new
    @feedlist = Feedback.paginate(:page => params[:page]).order('id DESC')

    # 恢复刚才输入的信息
    if("vcode_error" == request[:notice])
      flash[:content] = cookies[:feedback_content]
      flash[:name] = cookies[:feedback_name]
      flash[:email] = cookies[:feedback_email]
    end

    if(cookies[:notice] == 'send_successfully')
      cookies[:notice] = nil
      flash[:notice] = 'send_successfully'
    end
  end

  # POST: 保存反馈内容
  def create

    # 验证码
    unless simple_captcha_valid?
      cookies[:feedback_content] = params[:feedback][:content]
      cookies[:feedback_name] = params[:feedback][:name]
      cookies[:feedback_email] = params[:feedback][:email]
      redirect_to action: "index", notice: 'vcode_error'
      return
    end

  	@feedback = Feedback.new(params[:feedback])
  	if(session[:user] != nil)
  		@feedback.userid = session[:user].id
  	else
  		@feedback.userid = 0
  	end
  	@feedback.name = '匿名' if(@feedback.name == nil or @feedback.name == '')
    @feedback.name = htmlEncode(@feedback.name)
    @feedback.content = htmlEncode(@feedback.content)

  	respond_to do |format|
  		if @feedback.save
        cookies[:notice] = 'send_successfully'
	  		format.html { redirect_to action: "index" }
	  	else
	  		format.html { redirect_to action: "index", notice: 'send_error' }
	  	end
  	end
  end

  # GET
  def sitemap
    xml = '<?xml version="1.0" encoding="UTF-8"?>'
    xml << '<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
    xml << ' xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"'
    xml << ' xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
    xml << '<url>'
    xml << '<loc>http://www.ttbiji.com/</loc>'
    xml << '<changefreq>weekly</changefreq>'
    xml << '<priority>0.9</priority>'
    xml << '</url>'

    # 主路径
    arr = [];
    arr << 'http://www.ttbiji.com/memo'
    arr << 'http://www.ttbiji.com/rili'
    arr << 'http://www.ttbiji.com/feedback'
    arr << 'http://www.ttbiji.com/about'
    arr << 'http://www.ttbiji.com/plan'
    arr << 'http://www.ttbiji.com/user/reg'
    arr.each do |url|
      xml << '<url>'
      xml << '<loc>%s</loc>' % url
      xml << '<priority>0.8</priority>'
      xml << '</url>'
    end

    # 文档共享
    docs = DocMain.select('id, userid, updated_at').where(:shareid => 1).order("updated_at desc")
    docs.each do |doc|
      xml << '<url>'
      xml << '<loc>http://www.ttbiji.com%s</loc>' % [ getDetailUrl(doc)]
      xml << '<priority>0.7</priority>'
      xml << '<lastmod>%s</lastmod>' % doc.updated_at.in_time_zone(+8.hours).strftime('%Y-%m-%dT%H:%M:%S+08:00')
      xml << '</url>'
    end
    xml << '</urlset>'
    render :xml => xml
  end

private

  def htmlEncode(str)
    str.gsub(/&/, '&#38;').gsub(/</, '&lt;').gsub(/>/, '&gt;')
  end

end


